<!-- 游戏配置 -->
<template>
  <div class="tableMaxHight">
    <el-tabs v-model="data.gameType" type="card" class="demo-tabs" @tab-change="handleClick" style="user-select: none;">
      <el-tab-pane v-for="item in GAMETYPE" :label="item.label + '配置'" :name="item.value" />
    </el-tabs>
    <SearchTable :query="data.query" :list="data.list" :total="data.total" @changeSize="changeSize"
      @changePage="changePage" @search="getSearchList" @reset="resetDetails()" @changeTh="data.dialogVisible = true"
      style="padding: 0">
      <template #form>
        <Operator ref="OperatorRef" @query="queryItem" />
        <el-form-item label="游戏：">
          <el-select v-model="data.query.game_id" placeholder="请选择" filterable>
            <el-option label="全部" :value="-1" />
            <el-option v-show="item.type == data.query.game_type" v-for="item in indexStore.gameArray" :key="item.value"
              :label="'【' + item.value + '】' + item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </template>
      <template #button>
        <el-button type="danger" @click="getCommercialList(-1),data.isShowMaintain = true">维护游戏</el-button>
      </template>
      <template #table>
        <template v-for="(item, index) in data.fields" :key="index">
          <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width"
            show-overflow-tooltip>
            <template #header>
              <el-tooltip v-if="item.tips" effect="dark" placement="top">
                <template #content> {{ item.tips }} </template>
                <el-icon class="ques-tips">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
              {{ item.label }}
            </template>
            <template v-if="item.prop == 'agent_id'" #default="scope">
              {{ selectToLabel(indexStore.agentArray, scope.row.agent_id) }}
            </template>
            <template v-if="item.prop == 'game_id'" #default="scope">
              <div class="gameIcon">
                <div><img class="game-icon" :src="selectToLabel(GAMEICON, scope.row.game_id)" alt=""></div>
                {{ selectToLabel(indexStore.gameArray, scope.row.game_id) }}
              </div>
            </template>
            <template v-if="item.prop == 'game_type'" #default="scope">
              <el-tag>{{ selectToLabel(GAMETYPE, scope.row.game_type) }}</el-tag>
            </template>
            <template v-if="item.prop == 'trial_path'" #default="scope">
              <el-button type="success" size="small" :disabled="selectToLabel(data.gamePathList, scope.row.game_id,'id','id')?false:true" @click="trialPathGame(scope.row)">试玩游戏</el-button>
              <!-- <div class="flexCenter">
                <p class="text-cut details" @click="copyUrl(scope.row.trial_path, false)" style="width: 280px;">{{
                  scope.row.trial_path }}</p>
                <el-tooltip effect="dark" placement="top" content="编辑试玩路径">
                  <el-button class="marginL10" round size="small" type="warning" :icon="Edit"
                    @click="editGameUrl(scope.row, false)" />
                </el-tooltip>
              </div> -->
            </template>
            <template v-if="item.prop == 'a_slots_rtp'" #default="scope">
              {{ BigHundred(scope.row.pg_game.a_slots_rtp) }}%
            </template>
            <template v-if="item.prop == 'a_slots_rtptype'" #default="scope">
              <el-tag>{{ scope.row.pg_game.a_slots_rtptype ? selectToLabel(RtpType, scope.row.pg_game.a_slots_rtptype) : '-'
                }}</el-tag>
            </template>
            <template v-if="item.prop == 'a_slots_auto'" #default="scope">
              <el-tag :type="scope.row.pg_game.a_slots_auto ? 'danger' : 'success'">{{
                scope.row.pg_game.a_slots_auto ? '关闭' : '开启' }}</el-tag>
            </template>
            <template v-if="item.prop == 'a_slots_maxwin'" #default="scope">
              {{ scope.row.pg_game.a_slots_maxwin }}
            </template>
            <template v-if="item.prop == 'a_slots_amount'" #default="scope">
              <span v-for="(second, two) in scope.row.amount" :key="two">{{ second }}
                <span v-if="two != scope.row.amount.length - 1">,</span>
              </span>
            </template>
            <template v-if="item.prop == 'show'" #default="scope">
              <el-tag :type="scope.row.show ? 'success' : 'danger'">{{ selectToLabel(DEMOPLAY, scope.row.show)
                }}</el-tag>
            </template>
            <template v-if="item.prop == 'status'" #default="scope">
              <el-tag :type="scope.row.status ? 'primary' : 'danger'">
                {{ selectToLabel(GameStatus, scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
        </template>
        <el-table-column label="维护游戏" width="115" align="center">
          <template #header>
            <el-tooltip effect="dark" content="维护游戏/开启游戏：控制游戏维护开启的按钮" placement="top">
              <el-icon class="ques-tips">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
            维护游戏
          </template>
          <template #default="scope">
            <el-button :type="scope.row.status ? 'danger' : 'success'" v-permiss="'/system/changeManager'" size="small"
              @click="handleChange(scope.row)">
              {{ scope.row.status ? '维护游戏' : '开启游戏' }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" :width="data.gameType == 2 ? 300 : 150" align="center">
          <template #header>
            <el-tooltip effect="dark" placement="top">
              <template #content> 群控设置：设置luck win的调控配置控制输赢 <br />编辑：重新编辑此游戏的信息 </template>
              <el-icon class="ques-tips">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
            详情
          </template>
          <template #default="scope">
            <div class="flex">
              <el-button type="danger" v-if="data.gameType == 2 && scope.row.game_id == 100003 ? true : false"
                v-permiss="'/system/destroyManager'" size="small" @click="checkDetails(scope.row, 'control')">
                群控设置
              </el-button>
              <div style="width: 72px;height: 36px;margin-left: 12px;"
                v-if="data.gameType == 2 && scope.row.game_id != 100003 ? true : false"></div>
              <el-button type="success" v-permiss="'/system/destroyManager'" size="small"
                @click="checkDetails(scope.row, 'check')">
                查 看
              </el-button>
              <el-button type="primary" v-permiss="'/system/destroyManager'" size="small"
                @click="checkDetails(scope.row, 'edit')">
                编 辑
              </el-button>
            </div>
          </template>
        </el-table-column>
      </template>
    </SearchTable>

    <!-- 变更表头弹框 -->
    <tableHeader :dialogVisible="data.dialogVisible" :list="data.fields" @cancel="data.dialogVisible = false"
      @resetData="resetData"></tableHeader>

    <!-- 游戏路径 -->
    <GameUrl :show="data.isShowGameUrl" :isShowUrl="data.isShowUrl" :checkedItem="data.checkedItem"
      @onHideDetails="onHideDetails" />

    <!-- 游戏配置 -->
    <Config :show="data.isShowDetails" :showDisable="data.isDisableUser" :checkedItem="data.checkedItem"
      @onHideDetails="onHideDetails" />

    <!-- 群控配置 -->
    <Control :show="data.isShowControl" :checkedItem="data.checkedItem" @onHideDetails="onHideDetails" />

    <!-- 批量维护游戏 -->
    <el-dialog v-model="data.isShowMaintain" title="维护游戏" :close-on-click-modal="false" :close-on-press-escape="false"
      top="25vh" @close="onHideDetails">
      <form-item title="游戏状态" value="status">
        <el-radio-group v-model="data.queryDetails.status" size="large">
          <el-radio-button label="关闭游戏" :value="0" />
          <el-radio-button label="开启游戏" :value="1" />
        </el-radio-group>
      </form-item>
      <form-item title="商户类别" v-if="!indexStore.is_general_agent">
        <el-select v-model="data.queryDetails.operated_id" placeholder="请选择" filterable @change="getCommercialList">
          <el-option label="全部" :value="-1" />
          <el-option class="flexDetween" v-for="item in indexStore.operatorArray" :key="item.value"
            :label="'【' + item.value + '】' + item.label" :value="item.value">
            【{{ item.value }}】{{ item.label }}
            <el-tag size="small" :type="item.value == 1 ? 'success' : item.type == 1 ? 'danger' : 'warning'"
              style="font-size:10px;">
              {{ item.value == 1 ? '直营' : item.type == 1 ? '多货币' : '正常总代' }}
            </el-tag>
          </el-option>
        </el-select>
      </form-item>
      <form-item title="商户" :pass="true">
        <el-select class="imWidth100" v-model="data.queryDetails.agent_ids" placeholder="请选择" filterable multiple
          @change="chooseAgent">
          <el-option label="全部" :value="-1" />
          <el-option v-for="item in data.commercialArray" :key="item.id" :label="'【' + item.id + '】' + item.agent_name"
            :value="item.id" />
        </el-select>
      </form-item>
      <form-item title="游戏" :pass="true" value="game_id" v-if="data.gameType ? true : false">
        <el-select class="imWidth100" v-model="data.queryDetails.game_ids" placeholder="请选择游戏" filterable multiple
          @change="chooseGame">
          <el-option label="全部" :value="-1" />
          <el-option v-for="(item, index) in indexStore.gameArray" :key="index"
            :label="'【' + item.value + '】' + item.label" :value="item.value"/>
        </el-select>
      </form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="info" @click="onHideDetails">取 消</el-button>
          <el-button icon="CircleCheck" type="primary" size="small" @click="maintainGame">确 认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRefs, onMounted, computed } from 'vue'
import axios from 'axios'
import { Edit } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Operator, { type QueryType } from '@/components/FormItem/Operator.vue'
import FormItem from '@/components/FormItem/FormItem.vue'
import tableHeader from '@/components/tableHeader/tableHeader.vue'
import SearchTable from '@/components/SearchTable/SearchTable.vue'
import GameUrl from '@/views/configManage/components/gameUrl.vue'
import Config from '@/views/configManage/components/config.vue'
import Control from '@/views/configManage/components/control.vue'
import { getGame, editGame, editMaintainGame } from '@/api/game'
import { getAgentApiList } from '@/api/merchant'
import { GAMETYPE, DEMOPLAY, GAMEICON, GameStatus, RtpType } from '@/config/eunm'
import { selectToLabel, setSemicolonToArr } from '@/utils/index'
import { BigHundred, BigWan } from '@/utils/math'
import { useStore } from '@/stores/index'
const indexStore = useStore()

const data = reactive({
  query: {
    page: 1,
    size: 50,
    game_type: 1,
    agent_id: -1,
    operated_id: -1,
    game_id: -1,
  },
  list: [],
  total: 0,
  gameType: 1,
  queryDetails: {
    operated_id: -1,
    status: 0,
    game_ids: [],
    agent_ids: [],
    is_all: 0,
  },
  commercialArray: [] as any[],
  fields: [
    { label: '商户昵称', prop: 'agent_id', width: '150', visible: true, tips: '商户的名称' },
    { label: '游戏名称', prop: 'game_id', width: '', visible: true, tips: '游戏名称的描述说明' },
    { label: '游戏类型', prop: 'game_type', width: '120', visible: true, tips: '此游戏的类型，区分为百人、MiniGame 、老虎机' },
    { label: '试玩路径', prop: 'trial_path', width: '120', visible: true, tips: '游戏试玩的路径' },
    { label: 'RTP设定', prop: 'a_slots_rtp', width: '120', visible: true, tips: '游戏的回报率设定；值越高玩家盈利机会越高' },
    { label: 'RTP类型', prop: 'a_slots_rtptype', width: '120', visible: true, tips: '游戏的回报率类型' },
    { label: '止损止赢开关', prop: 'a_slots_auto', width: '150', visible: true, tips: 'slot的AUTO附加功能，开启后，玩家在游戏内自动旋转时，可以设定条件，达到输赢条件停止自动旋转' },
    { label: '倍数限制', prop: 'a_slots_maxwin', width: '120', visible: true, tips: '玩家在游戏内每局赢奖倍数限制,此倍数与总押注相乘为每局最高可赢取额度' },
    { label: '投注金额', prop: 'a_slots_amount', width: '200', visible: true, tips: '游戏的单押投注额度展示；游戏的总押注=单押额*押注等级（1~10）*游戏线数' },
    { label: '状态', prop: 'status', width: '100', visible: true, tips: '游戏维护和开启' },
  ],
  dialogVisible: false,
  isShowDetails: false,
  isDisableUser: false,
  isShowGameUrl: false,
  isShowMaintain: false,
  isShowUrl: false,
  isShowControl: false,
  checkedItem: {} as any,
  baseUrl: 'https://api.omgapi.cc',
  gamePathList:[],
  app_id: 0,
  token: '',
})

computed(() => {
  return data.gameType == -1 ? true : false
})

// 选择游戏tab
const handleClick = async () => {
  data.query.game_type = data.gameType
  data.fields = [
    { label: '商户昵称', prop: 'agent_id', width: '150', visible: true, tips: '商户的名称' },
    { label: '游戏名称', prop: 'game_id', width: '', visible: true, tips: '游戏名称的描述说明' },
    { label: '游戏类型', prop: 'game_type', width: '120', visible: true, tips: '此游戏的类型，区分为百人、MiniGame 、老虎机' },
    { label: '试玩路径', prop: 'trial_path', width: '120', visible: true, tips: '游戏试玩的路径' },
    { label: 'RTP设定', prop: 'a_slots_rtp', width: '120', visible: data.gameType == 1 ? true : false, tips: '游戏的回报率设定；值越高玩家盈利机会越高' },
    { label: 'RTP类型', prop: 'a_slots_rtptype', width: '120', visible: data.gameType == 1 ? true : false, tips: '游戏的回报率类型' },
    { label: '止损止赢开关', prop: 'a_slots_auto', width: '150', visible: data.gameType == 1 ? true : false, tips: 'slot的AUTO附加功能，开启后，玩家在游戏内自动旋转时，可以设定条件，达到输赢条件停止自动旋转' },
    { label: '倍数限制', prop: 'a_slots_maxwin', width: '120', visible: data.gameType == 1 ? true : false, tips: '玩家在游戏内每局赢奖倍数限制,此倍数与总押注相乘为每局最高可赢取额度' },
    { label: '投注金额', prop: 'a_slots_amount', width: '180', visible: data.gameType == 1 ? true : false, tips: '游戏的单押投注额度展示；游戏的总押注=单押额*押注等级（1~10）*游戏线数' },
    { label: '状态', prop: 'status', width: '100', visible: true, tips: '游戏维护和开启' },
  ]
  resetDetails()
}

// 商户类别 + 商户
const queryItem = (item: QueryType) => {
  data.query.agent_id = item.agent_id
  data.query.operated_id = item.operated_id
}

onMounted(async () => {
  getGameInfo()
  getSearchList()
})

const getSearchList = async () => {
  indexStore.setPageLoading(true)
  let res = await getGame(data.query)
  indexStore.setPageLoading(false)
  res.data?.list?.forEach((item: any) => {
    item.amount = setArrBetFace(item.pg_game.a_slots_amount)
  })
  data.list = res.data?.list
  data.total = res.data.total
}

// 详情
const checkDetails = async (row: any, type: string) => {
  if (type == 'control') {
    data.isShowControl = true
  } else {
    if (type == 'check') {
      data.isDisableUser = true
    } else {
      data.isDisableUser = false
    }
    data.isShowDetails = true
  }
  Object.assign(data.checkedItem, row)
}

const setArrBetFace = (str: string) => {
  let arr = [], newArr = [] as any[]
  arr = setSemicolonToArr(str)
  arr[0]?.forEach((item: any) => {
    newArr.push(BigWan(item))
  })
  return newArr
}

// 试玩路径
const getGameInfo = () => {
  axios({
    url: data.baseUrl + '/api/v1/pg/live-api/games',
    headers: {
      'content-type': 'application/json;charset=utf-8',
    },
    method:'GET',
  }).then(res =>{
    data.gamePathList = res.data.data.games
    data.app_id = res.data.data.app_id
    data.token = res.data.data.token
  })
}
const trialPathGame = (row: any) => {
  axios({
    url: data.baseUrl + '/api/usr/ingame',
    headers: {
      'content-type': 'application/json;charset=utf-8',
    },
    method:'POST',
    data:JSON.stringify({
      gameid: JSON.stringify(row.game_id),
      lang: 'en',
      nick: JSON.stringify(row.game_id),
      appid: JSON.stringify(data.app_id),
      token: data.token,
    }),
  }).then(res =>{
    if(!res.data.code){
      window.open(res.data.data.gameurl)
    }else{
      ElMessage.error('复制成功')
    }
  })
}
// 修改游戏路径
const editGameUrl = (row: any, show: boolean) => {
  data.isShowUrl = show
  data.isShowGameUrl = true
  Object.assign(data.checkedItem, row)
}
// 复制试玩路径
const copyUrl = (url: string, type: boolean) => {
  if (type) {
    let oInput = document.createElement("input");
    oInput.value = url
    document.body.appendChild(oInput)
    oInput.select() //选择对象
    document.execCommand("Copy") //执行浏览器复制命令
    document.body.removeChild(oInput)
    ElMessage.success('复制成功')
  } else {
    window.open(url)
  }
}

// 开启-关闭
const handleChange = (row: { test_account: string; status: number; game_id: number; agent_id: number }) => {
  let msg = row.status == 1 ? '确认是否关闭游戏？' : '确认是否开启游戏？',
    dataRow = JSON.parse(JSON.stringify(row));
  ElMessageBox.confirm(msg, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    dataRow.status = dataRow.status ? 0 : 1
    let res = await editGame(dataRow)
    ElMessage({
      type: 'success',
      message: '操作成功'
    })
    getSearchList()
  }).catch(() => { })
}

// 选择总代-查询总代下所有商户
const getCommercialList = async (id: number) => {
  data.queryDetails.agent_ids = []
  data.queryDetails.game_ids = []
  let res = await getAgentApiList({ operated_id: id })
  data.commercialArray = res.data as any
}
// 维护游戏
const maintainGame = async () => {
  let query = JSON.parse(JSON.stringify(data.queryDetails));
  if(!query.agent_ids.length){
    return ElMessage.error('请选择商户')
  }
  if(!query.game_ids.length){
    return ElMessage.error('请选择游戏')
  }
  // 选择全部
  const all = data.queryDetails.agent_ids.find((item: number) => item == -1)
  const allGame = data.queryDetails.game_ids.find((item: number) => item == -1)
  if (all) {
    query.agent_ids = []
    indexStore.agentArray.forEach((item: any) => {
      query.agent_ids.push(item.value)
    })
  }
  if (allGame) {
    query.game_ids = []
    indexStore.gameArray.forEach((item: any) => {
      query.game_ids.push(item.value)
    })
  }
  if(all && allGame){
    query.is_all = 1
  }else{
    query.is_all = 0
  }
  if (query.game_ids.length == 1 && query.game_ids[0] == -1) {
    return ElMessage.error(`请勿重复${query.status ? '开启' : '关闭'}游戏操作！`)
  }
  await editMaintainGame(query);
  ElMessage.success('操作成功')
  onHideDetails(false)
  getSearchList()
}
const chooseAgent = async (row: any) => {
  const all = row.find((item: number) => item == -1)
  if (all) {
    data.queryDetails.agent_ids = [-1] as any
  } else {
    data.queryDetails.agent_ids = row
  }
}
const chooseGame = async (row: any) => {
  const all = row.find((item: number) => item == -1)
  if (all) {
    data.queryDetails.game_ids = [-1] as any
  } else {
    data.queryDetails.game_ids = row
  }
}

// 修改页数
const changeSize = (val: number) => {
  data.query.size = val
  getSearchList()
}

const changePage = (val: number) => {
  data.query.page = val
  getSearchList()
}

// 重置表头
const resetData = (val: any) => {
  data.fields = val
}

// 重置
const onHideDetails = (show: boolean) => {
  data.isShowDetails = false
  data.isDisableUser = false
  data.dialogVisible = false
  data.isShowGameUrl = false
  data.isShowControl = false
  data.isShowMaintain = false
  data.queryDetails = {
    operated_id: -1,
    status: 0,
    game_ids: [],
    agent_ids: [],
    is_all: 0,
  }
  if (show) {
    data.query = {
      page: data.query.page,
      size: data.query.size,
      game_type: data.gameType,
      operated_id: data.query.operated_id,
      agent_id: data.query.agent_id,
      game_id: data.query.game_id,
    }
    getSearchList()
  }
}
const OperatorRef = ref<any>()
const resetDetails = () => {
  data.query = {
    page: 1,
    size: 50,
    game_type: data.gameType,
    operated_id: -1,
    agent_id: -1,
    game_id: -1,
  }
  OperatorRef.value.onHideDetails()
  getSearchList()
}
</script>

<style scoped lang="scss"></style>
